class ProductsController < ApplicationController
  before_filter :login_required,:only=>[:favorite]
  before_filter :find_user,:only=>[:favorite,:remove_favorite]
  #  before_filter :check_administrator_role,:except => [:index, :show,:confirm,:favorite,:remove_favorite]
  #  before_filter :find_cart

  # GET /products
  # GET /products.xml
  def index
    @products = Product.paginate :page => params[:page],:per_page => 5,:order=>"id desc"
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml =>  @products.to_xml }
    end
  end

  # GET /products/1
  # GET /products/1.xml
  def show
    @product = Product.find(:first,:conditions=>["uuid=?",params[:id]])

    respond_to do |format|
      format.html 
      format.xml  { render :xml => @product}
    end
  end

  # GET /products/new
  # GET /products/new.xml
  def new
    @product = Product.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @product }
    end
  end

  # GET /products/1/edit
  def edit
    @product = Product.find(params[:id])
  end

  # POST /products
  # POST /products.xml
  def create
    @product = Product.new(params[:product])

    respond_to do |format|
      if @product.save
        flash[:notice] = 'Product was successfully created.'
        format.html { redirect_to(products_path) }
        format.xml  { render :xml => @product, :status => :created, :location => @product }
      else
        format.html { render :action => "new" } # new.html.erb
        format.xml  { render :xml => @product }
      end
    end
  end

  def favorite
    @product = Product.find(params[:id])
    unless @product.collectors.include?(@user)
      @user.favors << @product
      flash[:notice] = '添加到收藏夹成功.'
    end
    respond_to do |format|
      format.html { redirect_to('/store/my_favorite') }
    end
  end

  def remove_favorite
    @product = Product.find(params[:id])
    if @product.collectors.include?(@user)
      @user.favors.delete(@product)
      flash[:notice] = '更新成功.'
    end
    respond_to do |format|
      format.html { redirect_to('/store/my_favorite') }
    end
  end

  # PUT /products/1
  # PUT /products/1.xml
  def update
    @product = Product.find(params[:id])

    respond_to do |format|
      if @product.update_attributes(params[:product])
        flash[:notice] = 'Product was successfully updated.'
        format.html { redirect_to(:controller=>:products,:action=>:show,:id=>@product.uuid) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /products/1
  # DELETE /products/1.xml
  def destroy
    @product = Product.find(params[:id])
    @product.destroy

    respond_to do |format|
      format.html { redirect_to(products_url) }
      format.xml  { head :ok }
    end
  end

  def search
    if params[:keyword]
      price = ""
      brand_id = ""
      page = 1
      price = params[:price] if params[:price]
      brand_id = params[:query][:brand_id] if params[:query]
      page = params[:page] if params[:page]

      @products = Product.search_without_brand(params[:keyword],price,brand_id,page )
      respond_to do |format|
        format.html  # search.html.erb
        format.xml  { render :xml => @products }
      end
    end
  end

  def update_sort_order
    json_data =JSON::parse(params[:json])
    json_data.each {|i| Product.update(i["id"],:sort_order=>i["order"])}
    render :text => "true"
  end

  def re_active
    @products = Product.paginate :conditions=>"DATE_ADD(`active_date`,INTERVAL `live_date` DAY) < now()",
      :order=>'sort_order desc',:page => params[:page],:per_page => 5
  end

  def update_active
    if params[:product]
      params[:product].keys.each do |id|
        Product.update(id,:active_date=>DateTime.now.strftime("%Y-%m-%d")) if  params[:product][id]["active"] == "1"
      end
    end
    redirect_to :action => "re_active"
  end

  def scraper
    if params[:site]
      count = Product.scraper(params[:site],params[:category_id],params[:brand_id])
      respond_to do |format|
        if count > 0
          flash[:notice] = "#{count} products was successfully created."
          format.html { redirect_to("/store") }
          #          format.xml  { head :ok }
        else
          format.html { render :action => "scraper" }
          #          format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
        end
      end
    end
  end

  def test_scraper
    if !params[:site].blank? && !params[:xpath].blank?
      doc = open(params[:site]){ |f| Hpricot(f)}
      iconv=Iconv.new("UTF-8//IGNORE","utf8")
      @result =  iconv.iconv(doc.search(params[:xpath]).to_html)
    end

    if !params[:regex].blank? && !params[:content].blank?
      doc = Hpricot(params[:content])
      @reg_result  = doc.inner_text.scan(Regexp.new(params[:regex])).join(",")
    end
  end

end

